<!--
 * @author guojiteng
 -->
<template>
  <div id="adminmanage">
    <el-collapse-transition>
      <div v-show="searchshow" class="course-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="searchQuery.systemName"
          placeholder="请输入系统名称搜索"
          class="search-input"
          @keyup.enter.native="handleFilter"
        />
        <div class="course-search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
          <!-- <el-button class="filter-item" type="primary" @click="update">更新</el-button> -->
          <span class="course-search-more" @click="searchshow = !searchshow">
            更多筛选条件
            <i class="el-icon-arrow-down" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <el-collapse-transition>
      <div v-show="!searchshow" class="course-search separate">
        <div class="course-search-inner">
          <el-row>
            <el-col :span="8">
              <div class="search-inner-item">
                <div class="item-label">系统分类</div>
                <el-select
                  v-if="dictList.length>5"
                  v-model="searchQuery.category"
                  style="width:80%;"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in dictList"
                    :key="item.id"
                    :label="item.dictName"
                    :value="item.id"
                  />
                </el-select>
                <el-radio-group v-else v-model="searchQuery.category">
                  <el-radio
                    v-for="(item,key) in dictList"
                    :key="key"
                    style="margin-top:5px;"
                    :label="item.id"
                  >{{ item.dictName }}</el-radio>
                </el-radio-group>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="search-inner-item">
                <div class="item-label">系统名称</div>
                <el-input
                  v-model.trim="searchQuery.systemName"
                  style="width: 300px;"
                  class="filter-item"
                  placeholder="请输入系统名称搜索"
                />
              </div>
            </el-col>
            <el-col :span="8">
              <div class="search-inner-item">
                <div class="item-label">状态</div>
                <el-checkbox-group v-model="choose" style="margin-top:15px;">
                  <el-checkbox label="0">启用</el-checkbox>
                  <el-checkbox label="1">禁用</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="course-search-btn">
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
          <span class="course-search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <div class="btn-container">
      <div class="btn-container-title">
        <span>对接系统管理</span>
      </div>
      <div class="btn-container-btns">
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">新建</el-button>
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleDeletes">批量删除</el-button>
      </div>
    </div>
    <div class="table">
      <el-table
        ref="rolemantable"
        v-loading="listLoading"
        :data="list"
        class="tableScope"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="categoryName" label="系统分类" width="150" show-overflow-tooltip />
        <el-table-column prop="systemName" label="系统名称" show-overflow-tooltip width="150" />
        <el-table-column prop="accessAddress1" label="访问地址" show-overflow-tooltip min-width="150" />
        <el-table-column prop="secretKey1" label="系统私钥" show-overflow-tooltip width="150" />
        <el-table-column prop="secretKey2" label="系统公钥" show-overflow-tooltip width="150" />
        <el-table-column prop="secretKey3" label="对接系公钥" show-overflow-tooltip width="150" />
        <el-table-column prop="leaderName" label="对接负责人" width="150" show-overflow-tooltip />
        <el-table-column prop="leaderPhone" label="手机号" show-overflow-tooltip width="150" />
        <el-table-column prop="leaderCompany" label="单位" show-overflow-tooltip width="150" />
        <el-table-column prop="acceptIp" label="可访问ip" show-overflow-tooltip width="150" />
        <el-table-column prop="statusName" label="状态" show-overflow-tooltip width="80" />
        <!-- <el-table-column prop="status" label="状态" width="80" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.status=='0'?'启用':'禁用' }}</span>
          </template>
        </el-table-column>-->
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="btn-pagion fix">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="pageQuery.page"
        :limit.sync="pageQuery.pageSize"
        @pagination="getList"
      />
    </div>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      center
      width="800px"
    >
      <el-form
        ref="addForm"
        v-loading="submitloading"
        :model="addForm"
        :rules="addRules"
        class="dataForm"
        label-position="right"
        label-width="120px"
        style="height:410px"
      >
        <el-form-item label="系统分类" prop="category">
          <el-select
            v-if="dictList.length > 5"
            v-model.trim="addForm.category"
            style="width: 100%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in dictList"
              :key="item.id"
              :label="item.dictName"
              :value="item.dictValue"
              :title="item.dictName"
            />
          </el-select>
          <el-radio-group v-else v-model="addForm.category">
            <el-radio
              v-for="(item,key) in dictList"
              :key="key"
              style="margin-top:5px;"
              :title="item.dictName"
              :label="item.dictValue"
            >{{ item.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="系统ID" prop="appId">
          <el-input v-model.trim="addForm.appId" placeholder="请输入系统ID" />
        </el-form-item>
        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model.trim="addForm.systemName" placeholder="请输入系统名称" />
        </el-form-item>
        <el-form-item label="访问地址" prop="accessAddress1">
          <el-input v-model.trim="addForm.accessAddress1" placeholder="请输入访问地址" />
        </el-form-item>
        <el-form-item label="系统私钥" prop="secretKey1">
          <el-input v-model.trim="addForm.secretKey1" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" prop="secretKey1" placeholder="请输入系统私钥" />
        </el-form-item>
        <!-- 	<el-form-item label="公钥" prop="secretKey1">
					<el-input v-model.trim="addForm.secretKey1" placeholder="请输入初始密钥1" />
				</el-form-item> -->

        <!-- 		<el-form-item label="访问地址2">
					<el-input v-model.trim="addForm.accessAddress2" placeholder="请输入访问地址2" />
				</el-form-item> -->
        <el-form-item label="系统公钥" prop="secretKey2">
          <el-input v-model.trim="addForm.secretKey2" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输系统公钥" />
        </el-form-item>
        <!-- 	<el-form-item label="访问地址3">
					<el-input v-model.trim="addForm.accessAddress3" placeholder="请输入访问地址3" />
				</el-form-item> -->
        <el-form-item label="对接系统公钥" prop="secretKey3">
          <el-input v-model.trim="addForm.secretKey3" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入对接系统公钥" />
        </el-form-item>
        <el-form-item label="对接负责人">
          <el-input v-model.trim="addForm.leaderName" placeholder="请输入对接负责人" />
        </el-form-item>
        <el-form-item v-if="addForm.leaderPhone" label="手机号码" prop="leaderPhone">
          <el-input v-model.trim="addForm.leaderPhone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item v-else label="手机号码">
          <el-input v-model.trim="addForm.leaderPhone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="单位名称">
          <el-input v-model.trim="addForm.leaderCompany" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="可访问IP">
          <el-input
            v-model.trim="addForm.acceptIp"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6}"
            placeholder="请输入可访问IP"
          />
          <span
            style="color:red;line-height: 19px"
          >如果您设置了可访问IP，只有在可访问IP列表中的IP可以访问系统。你可以配置多个IP地址或IP段，用英文分号隔开。举例：192.168.1.1;192.168.1.3-192.168.1.20;192.168.1.100</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="addForm.status">
            <el-radio label="ZT01">启用</el-radio>
            <el-radio label="ZT02">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogStatus==='create'" type="primary" @click="createStr()">随机生成字符串</el-button>
        <el-button style="padding: 10px 30px;" @click="dialogFormVisible = false">取消</el-button>

        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      title="生成随机字符串"
      :visible.sync="sjzfc"
      center
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form v-model="str" class="dataForm" label-position="right" label-width="90px" style="height:200px">
        <el-form-item label="字符串长度">
          <el-input v-model.trim="str.leng" placeholder="请输入字符串长度默认32" />
        </el-form-item>
        <el-form-item label="随机字符串">
          <el-input v-model.trim="str.value" disabled placeholder />
        </el-form-item>
        <el-form-item label="字符串类型">
          <el-radio-group v-model="str.type">
            <el-radio v-for="(item,key) in strType" :key="key" :label="item.value">{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="randomString()">生成</el-button>
        <el-button type="primary" @click="copy($event)">复制字符串</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  phone
} from '@/utils/validate'
import clipboard from '@/utils/clipboard'
import {
  mapGetters
} from 'vuex'
import {
  queryPage,
  add,
  get,
  update,
  deleteById,
  getDic
} from '@/views/dockingmanage/api/index'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import permission from '@/directive/permission/index.js' // 权限判断指令
// eslint-disable-next-line no-unused-vars
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  name: 'Adminmanage',
  components: {
    Pagination
  },
  directives: {
    permission,
    elDragDialog
  },
  data() {
    return {
      str: {
        leng: '',
        value: '',
        type: 0
      },
      strType: [{
        label: '16进制',
        value: 0
      },
      {
        label: '纯数字',
        value: 1
      },
      {
        label: '纯字母',
        value: 4
      },
      {
        label: '纯字母(大写)',
        value: 2
      },
      {
        label: '纯字母(小写)',
        value: 3
      }
      ],
      submitloading: false,
      sjzfc: false,
      checkArr: [],
      pageQuery: {
        page: 1,
        pageSize: 10
      },
      addForm: {
        category: '',
        systemName: '',
        appId: '',
        accessAddress1: '',
        accessAddress2: '',
        accessAddress3: '',
        secretKey1: '',
        secretKey2: '',
        secretKey3: '',
        status: 'ZT01',
        leaderName: '',
        leaderPhone: '',
        leaderCompany: '',
        acceptIp: ''
      },
      searchshow: true,
      searchQuery: {
        systemName: '',
        category: '',
        status: []
      },

      list: [],
      total: 0,
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        create: '新建',
        update: '编辑'
      },
      multipleSelection: [],
      dictList: [],
      choose: [],
      listLoading: false,
      addRules: {
        appId: [{
          required: true,
          message: '请填写系统ID',
          trigger: 'blur'
        }],
        systemName: [{
          required: true,
          message: '请填写系统名称',
          trigger: 'blur'
        }],
        accessAddress1: [{
          required: true,
          message: '请填写访问地址',
          trigger: 'blur'
        }],
        secretKey1: [{
          required: true,
          message: '请填写系统私钥',
          trigger: 'blur'
        }],
        secretKey2: [{
          required: true,
          message: '请填写系统公钥',
          trigger: 'blur'
        }],
        secretKey3: [{
          required: true,
          message: '请填写对接系统公钥',
          trigger: 'blur'
        }],
        leaderPhone: [{
          required: false
        },
        {
          validator: phone,
          trigger: 'blur'
        }
        ],
        status: [{
          required: true,
          message: '请选状态',
          trigger: 'blur'
        }],
        category: [{
          required: true,
          message: '请选系统分类',
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  created() {
    this.getDicList()
    this.getList()
  },
  methods: {
    // update() {
    //   this.$store.commit('changeImg', '425252525')// 其中idx为传入的参数
    // },
    copy(event) {
      clipboard(this.str.value, event)
    },
    // 复制到剪切板
    onCopy(e) {
      this.$message.success('复制成功!')
    },
    onError(e) {
      this.$message.error('复制失败')
    },
    // 生成随机字符串
    randomString() {
      // alert(this.str.type)
      // return false
      const len = this.str.leng || 32
      let chars = ''
      switch (this.str.type) {
        case 0:
          chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
          break
        case 1:
          chars = '0123456789'
          break
        case 2:
          chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
          break
        case 3:
          chars = 'abcdefghijklmnopqrstuvwxyz'

          break
        case 4:
          chars = 'abcdefGhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
          break
      }
      // var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      if (this.str.type === 0) {
        this.rand16(parseInt(len))
      } else {
        var maxPos = chars.length
        var pwd = ''
        for (let i = 0; i < len; i++) {
          pwd += chars.charAt(Math.floor(Math.random() * maxPos))
        }
        this.str.value = pwd
      }
    },
    rand16(c) {
      let num = ''
      for (let i = 0; i < c; i++) {
        var tmp = Math.ceil(Math.random() * 15)
        if (tmp > 9) {
          switch (tmp) {
            case (10):
              num += 'a'
              break
            case (11):
              num += 'b'
              break
            case (12):
              num += 'c'
              break
            case (13):
              num += 'd'
              break
            case (14):
              num += 'e'
              break
            case (15):
              num += 'f'
              break
          }
        } else {
          num += tmp
        }
      }
      this.str.value = num
    },
    createStr() {
      this.str.value = ''
      this.sjzfc = true
    },
    getDicList() {
      const obj = {
        dictCode: 'XTFL'
      }
      getDic(obj).then(res => {
        this.dictList = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
      })
    },

    getList() {
      if (this.choose.length > 0) {
        this.searchQuery.status = this.choose.join(',')
      } else {
        this.searchQuery.status = ''
      }
      Object.assign(this.searchQuery, this.pageQuery)
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPage(this.searchQuery).then(res => {
          this.listLoading = false
          this.list = res.data.data.rows || []
          this.total = res.data.data.total
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },

    handleFilter() {
      this.pageQuery.page = 1
      this.getList()
    },
    resettingBtn() {
      this.pageQuery.page = 1
      this.pageQuery.pageSize = 10
      for (const key in this.searchQuery) {
        this.searchQuery[key] = ''
      }
      this.choose = []
      this.getList()
    },

    handleCreate() {
      this.dialogStatus = 'create'
      for (const key in this.addForm) {
        this.addForm[key] = ''
      }
      this.addForm.status = 'ZT01'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({
          id: row.id
        }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.addForm) {
            this.addForm[key] = data[key]
          }
          this.addForm.id = data.id
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['addForm'].clearValidate()
          })
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleDeletes() {
      const arr = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          arr.push(item.id)
        })
        const ids = arr.join(',')
        this.deleteUser(ids)
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'warning'
        })
      }
    },
    handleDelete(row) {
      this.deleteUser(row.id)
    },
    deleteUser(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteById({
            ids: ids
          }).then(res => {
            this.$message.success('删除成功!')
            this.getList()
          })
        })
        .catch(() => {})
    },
    createData() {
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          add(this.addForm).then(res => {
            loading.close()
            this.$message.success('创建成功！')
            this.dialogFormVisible = false
            this.pageQuery.size = 1
            this.getList()
            // eslint-disable-next-line handle-callback-err
          }).catch(err => {
            loading.close()
          })
        }
      })
    },
    updateData() {
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          update(this.addForm)
            .then(res => {
              loading.close()
              this.$message.success('编辑成功！')
              this.dialogFormVisible = false
              this.pageQuery.size = 1
              this.getList()
            })
          // eslint-disable-next-line handle-callback-err
            .catch(err => {
              loading.close()
            })
        }
      })
    },
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">
	$dark_gray: #bfced6;
// $mainColor: #18a5fd;
.custom-tree-node {
  .companyName {
    width: 306px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
#adminmanage {
  padding: 10px 20px 10px 10px;
  .course-search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 20px;
      }
    }
    .search-input {
      width: 60%;
      position: relative;
      &:after {
        content: "";
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .course-search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .course-search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }
    &.merge {
      height: 50px;
      line-height: 50px;
    }
    &.separate {
      .course-search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }
          .el-input {
            position: relative;
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: "";
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
      .course-search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }
  .btn-container {
    display: flex;
    align-items: center;
    margin-top: 5px;
    margin-bottom: 5px;
    .btn-container-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      color: rgba(51, 51, 51, 1);
    }
  }
  .dataForm {
		width: 100%;
    .el-radio__label {
      display: inline-block;
      max-width: 380px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .el-checkbox__label {
    font-weight: 400;
  }
  .el-form-item__label {
    // width: 90px !important;
  }
  .el-form-item__content {
    // margin-left: 90px !important;
  }
}
</style>
